package cc.git.liuyan.test;

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.edge.EdgeOptions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

public class BatchCk_Test_1 {
    public static void main(String[] args) {
        System.setProperty("webdriver.edge.driver", "E:\\edgeDriver\\msedgedriver.exe");
        EdgeOptions edgeOptions = new EdgeOptions();
        //edgeOptions.addArguments("--headless"); //无头模式
        edgeOptions.addArguments("--remote-allow-origins=*");
        WebDriver driver = new EdgeDriver(edgeOptions);
        WebDriverWait defaultWait = new WebDriverWait(driver, Duration.ofSeconds(30));
        //
        driver.get("http://ntbms.yshlw.com/login");

        System.out.println(driver.getTitle());
        System.out.println(driver.getCurrentUrl());
        System.out.println(driver.getWindowHandle());
        System.out.println(String.join(",", driver.getWindowHandles()));

        String mainHandle = driver.getWindowHandle();
        List<String> oldHandleList = new ArrayList<>(driver.getWindowHandles());

        // 使用 JavaScript 打开新标签页
        //driver.get("https://www.baidu.com"); //get是替换当前标签页的url为新的，不会开启一个新标签页
        JavascriptExecutor js = (JavascriptExecutor) driver;
        js.executeScript("window.open('https://www.baidu.com', '_blank');");

        List<String> newHandleList = new ArrayList<>(driver.getWindowHandles());

        String newHanle = newHandleList.stream().filter(p -> !oldHandleList.contains(p)).findFirst().get();

        //此时代码还没有切换到新标签页 但是浏览器已经切换到新标签页了
        System.out.println(driver.getTitle());
        System.out.println(driver.getCurrentUrl());
        System.out.println(driver.getWindowHandle());
        System.out.println(String.join(",", driver.getWindowHandles()));

        //要手动将代码切换到新标签页，这样就和浏览器一致了
        driver.switchTo().window(newHanle);

        //此时代码切换到新标签页 和浏览器一致了
        System.out.println(driver.getTitle());
        System.out.println(driver.getCurrentUrl());
        System.out.println(driver.getWindowHandle());
        System.out.println(String.join(",", driver.getWindowHandles()));

        //关闭当前窗口  quit是退出浏览器
        driver.close();

        //代码还是旧窗口，但是浏览器中该窗口已关闭了，所以这里代码会报错，要手动切换到其它窗口
        driver.switchTo().window(mainHandle);
        System.out.println(driver.getTitle());
        System.out.println(driver.getWindowHandle());
        System.out.println(driver.getCurrentUrl());
        System.out.println(String.join(",", driver.getWindowHandles()));
    }
}
